<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Request;
use think\facade\Cache;

class Power extends Controller
{

    public function initialize()
    {
        error_reporting(5);//1+4
        //设置跨域头
        header('Access-Control-Allow-Origin: *');
        //token 验证登录信息是否有效
        $request = new Request();
        $g=$request->get();
        $p=$request->post();
        $token = '';
        (isset($g['token']) && !empty($g['token'])) and ($token = $g['token']);
        (isset($p['token']) && !empty($p['token'])) and ($token = $p['token']);
        if(empty($token)){
            js_code('
                    var str = localStorage.getItem("token");
                    if(str !=="" || str.length>0){
                        var preg = /(\?token=.*|\?.*)/i
                        var href = location.href.replace(preg,"");
                        location.href=(href+"?token="+str).replace(/[?]{2,}/g,"?");
                    }else{
                        location.href="/admin_login_out";
                    }   
            ');
        }
        $jwt = new \app\common\controller\publics\Jwt();
        if(!$jwt->is_token($g['token']) || empty(cookie('fwf_admin_name'))){
            $this->error('信息验证错误，请重新登录','/admin_login_out');
        }
    }
    //角色列表
    public function group_list(){
        //检查权限
        power_check();
        $title = '角色列表';
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);
        $this->assign('title',$title);

        $group_list = Db::name('group')->select();
        $this->assign('group_list',$group_list);



        return $this->fetch();
    }
    //修改，添加角色
    public function group_edit(Request $request){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $id = $request->param('id');
        $t = lang('group_add');
        if($id){
            $t = lang('group_edit');
        }
        $this->assign('title',$t);

        //获取分组权限信息
        $group = Db::name('group')->where('group_id','=',$id)->find();
        //获取菜单信息
        $menu_list = Db::name('menu')->select();
        $group_rules = explode(',',$group['group_rules']);
        $GLOBALS['tree']['id'] = 'menu_id';
        $GLOBALS['tree']['pid'] = 'menu_pid';
        $menu_list = get_leval_list(1,1,$menu_list);

        $this->assign('menu_list',$menu_list);
        $this->assign('group',$group);
        $this->assign('group_rules',$group_rules);
        return $this->fetch();
    }
    //保存角色
    public function group_save(Request $request){
        //检查权限
        power_check();
        $p = $request->post();
        $admin_id = cookie('fwf_admin_id');
        $validate = new \app\admin\validate\Power();
        if(!$validate->group_save($p)){
            $err = $validate->getError();
            $this->error(array_shift($err));
        }else{
            $group_rules = join(',',$p['group_rules']);
            $data = [
                'group_title'   => $p['group_title'],
                'group_status'  => $p['group_status'],
                'group_rules'   => $group_rules,
            ];
            if($p['group_id']){
                //修改
                $up_n = Db::name('group')->where('group_id','=',$p['group_id'])->data($data)->update();
                if($up_n){
                    fwf_log('修改分组权限信息，修改的ID：'.$p['group_id'].'，影响的行数：'.$up_n.'，操作管理员ID：'.$admin_id);
                }
                $this->success(lang('edit_success'),'/power/group_list/id/'.$p['group_id']);
            }else{
                //添加
                $insert_id = Db::name('group')->insertGetId($data);
                if($insert_id){
                    fwf_log('添加分组权限信息，添加的ID：'.$insert_id.'操作管理员ID：'.$admin_id);
                    $this->success(lang('add_success'),'/power/group_list/id/'.$insert_id);
                }
                $this->error(lang('add_fail'));
            }

        }

    }
    //删除角色
    public function group_del(Request $request){
        //检查权限
        power_check();
        $id = $request->param('id');
        $g = $request->get();
        if($id){
            $del_n = Db::name('group')->where('group_id','=',$id)->delete();
            if($del_n){
                $admin_id = cookie('fwf_admin_id');
                fwf_log('删除分组权限信息，删除的ID：'.$id.'，操作管理员ID：'.$admin_id.'，删除的条数：'.$del_n);
                $this->redirect('/power/group_list/?token='.$g['token']);
            }
        }
        $this->error(lang('del_fail'),'/power/group_list/?token='.$g['token']);
    }



    //管理员列表
    public function admin_list(){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $this->assign('title',lang('admin_list'));
        $member_list = Db::name('member')->where('is_admin','in',[1,2])->select();

        $this->assign('member_list',$member_list);

        return $this->fetch();
    }
    //添加，修改管理员
    public function admin_edit(Request $request){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $id = $request->param('id');
        $t  = lang('admin_add');
        if($id){
            $t = lang('admin_edit');
        }
        $this->assign('title',$t);

        $admin = Db::name('member')->where('member_id','=',$id)->find();
        $member_group_list = Db::name('group')->where('group_status','=',1)->select();

        $this->assign('admin',$admin);
        $this->assign('member_group_list',$member_group_list);

        return $this->fetch();
    }
    //保存管理员
    public function admin_save(Request $request){
        //检查权限
        power_check();
        $p = $request->post();
        $id = $p['member_id'];
        $admin_id = cookie('fwf_admin_id');
        $validate = new \app\admin\validate\Power();
        if(!$validate->admin_save($p)){
            $err = $validate->getError();
            $this->error(array_shift($err));
        }else{
            $data=[
                'member_user'   =>$p['member_user'],
                'member_sex'    =>$p['member_sex'],
                'member_phone'  =>$p['member_phone'],
                'member_qq'     =>$p['member_qq'],
                'member_email'  =>$p['member_email'],
                'is_admin'      =>$p['is_admin'],
                'member_group'  =>$p['member_group'],
            ];
            if($id){
                //修改
                if(!empty($p['member_password'])){
                    $member = Db::name('member')->where('member_id','=',$id)->find();
                    $data['member_password'] = md5_pass($p['member_password'],$member['member_salt']);
                }
                $up_n = Db::name('member')->where('member_id','=',$id)->data($data)->update();
                if($up_n){
                    fwf_log('修改管理员信息，管理员ID：'.$id.'，操作管理员ID:'.$admin_id.'，影响的行数：'.$up_n);
                }
                $this->success(lang('edit_success'),'/power/admin_edit/id/'.$id.'/?token='.$p['token']);
            }else{
                //添加
                //检测管理员名称是否重复
                $count = Db::name('member')->where('is_admin','in',[1,2])->where('member_user','=',$data['member_user'])->count();
                if($count>0){
                    $this->error('管理员名称不能重复','/power/admin_list/?token='.$p['token']);
                }
                if(!empty($p['member_password']) && !empty($p['member_salt'])){
                    $data['member_password'] = md5_pass($p['member_password'],$p['member_salt']);
                    $data['member_salt'] = $p['member_salt'];
                    $data['member_add_time'] = time();
                    $insert_id = Db::name('member')->insertGetId($data);
                    if($insert_id){
                        fwf_log('添加管理员信息，添加的管理员ID：'.$insert_id.'，操作管理员ID:'.$admin_id);
                        $this->success(lang('add_success'),'/power/admin_list/id/'.$insert_id.'/?token='.$p['token']);
                    }
                }
                $this->error(lang('add_fail'),'/power/admin_list/?token='.$p['token']);
            }
        }

    }
    //删除管理员,不能删除编号为1的原始超级管理员以及当前操作的管理员
    public function admin_del(Request $request){
        //检查权限
        power_check();
        $id = $request->param('id');
        $g = $request->get();
        $admin_id = cookie('fwf_admin_id');
        if($id && !in_array($id,[0,1,$admin_id])){
            $del_n = Db::name('member')->where('member_id','=',$id)->delete();
            if($del_n){
                fwf_log('删除管理员信息，删除的管理员ID：'.$id.'，操作管理员ID:'.$admin_id,'，影响的行数：'.$del_n);
                $this->redirect('/power/admin_list/?token='.$g['token']);
            }
        }
        $this->error(lang('del_fail'),'/power/admin_list/?token='.$g['token']);
    }

}
